import 'dart:io';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/utils/file_util.dart';
import 'package:safetymonitor/generated/assets.dart';

/// 版本更新提示弹框
class UpdateDialog extends StatefulWidget {
  const UpdateDialog({
    required this.version,
    required this.upDateContent,
    required this.isForce,
    required this.downloadAddress,
    super.key,
  });

  final String upDateContent;
  final bool isForce;
  final String version;
  final String downloadAddress;

  @override
  State<UpdateDialog> createState() => _UpdateDialogState();
}

class _UpdateDialogState extends State<UpdateDialog> {
  double _progress = 0; // 设置进度
  String filePath = ''; // 文件路径
  bool isExist = false; // 文件是否存在
  bool isDownLoad = false; // 是否正在下载

  @override
  void initState() {
    super.initState();
    init();
  }

  void init() async {
    // 获取文件路径
    filePath = await FileUtils.getSavePath(widget.downloadAddress);
    // 判断文件是否存在
    isExist = await File(filePath).exists();
    setState(() {});
  }

  /// 获取滚动条-不包含进度
  Widget getLinearProgress() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: [
          LinearProgressIndicator(minHeight: 15.w),
          AppGaps.vGap10,
          Text(
            '下载中...'.tr,
            style: TextStyle(fontSize: 14.sp, color: const Color(0xff071D56), decoration: TextDecoration.none),
          ),
          AppGaps.vGap10,
        ],
      ),
    );
  }

  /// 根据[_progress] 获取进度条
  Widget getProgressView() {
    return Visibility(
      visible: isDownLoad,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          children: [
            LinearProgressIndicator(
              minHeight: 15.w,
              value: _progress,
              backgroundColor: Colors.grey[200],
              valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
            ),
            AppGaps.vGap10,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '下载进度'.tr,
                  style: TextStyle(fontSize: 14.sp, color: const Color(0xff071D56), decoration: TextDecoration.none),
                ),
                Text(
                  '${(_progress * 100).toStringAsFixed(0)}%',
                  style: TextStyle(fontSize: 14.sp, color: const Color(0xff071D56), decoration: TextDecoration.none),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  //获取按钮显示
  Widget getButtonView() {
    return !isExist
        ? Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: ElevatedButton(
              style: ButtonStyle(
                  minimumSize: WidgetStateProperty.all(const Size(0, 40)),
                  shape: WidgetStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(40.r),
                  )),
                  backgroundColor: WidgetStateProperty.all(const Color(0xff2267C0))),
              onPressed: downFile,
              // 设置按钮为圆角
              child: Text(
                '立即安装'.tr,
                style: TextStyle(fontSize: 16.sp, color: Colors.white),
              ),
            ),
          )
        : Container(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ButtonStyle(
                        minimumSize: WidgetStateProperty.all(const Size(0, 40)),
                        shape: WidgetStateProperty.all(RoundedRectangleBorder(
                          side: BorderSide(color: const Color(0xff2267C0), width: 1.w),
                          borderRadius: BorderRadius.circular(40.r),
                        )),
                        backgroundColor: WidgetStateProperty.all(const Color(0xffD6E4F6))),
                    child: Text(
                      '重新下载'.tr,
                      style: TextStyle(fontSize: 16.sp, color: const Color(0xff2267C0)),
                    ),
                    onPressed: () async {
                      await FileUtils.delete(widget.downloadAddress);
                      downFile();
                    },
                  ),
                ),
                AppGaps.hGap14,
                Expanded(
                  child: ElevatedButton(
                    style: ButtonStyle(
                        minimumSize: WidgetStateProperty.all(const Size(0, 40)),
                        shape: WidgetStateProperty.all(RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(40.r),
                        )),
                        backgroundColor: WidgetStateProperty.all(const Color(0xff2267C0))),
                    onPressed: downFile,
                    child: Text(
                      '去安装'.tr,
                      style: TextStyle(fontSize: 16.sp, color: Colors.white),
                    ),
                  ),
                )
              ],
            ));
  }

  Future<void> downFile() async {
    SmartDialog.showLoading(backType: SmartBackType.normal, msg: '获取中...'.tr);
    await FileUtils.downloadFile(
      isShowLoading: false,
      type: 'application/vnd.android.package-archive',
      widget.downloadAddress,
      onReceiveProgress: (int value, int total) {
        // 第一次获取到下载进度
        if (!isDownLoad) {
          SmartDialog.dismiss();
          isDownLoad = true;
          init();
        }
        // if (!isDownLoad) SmartDialog.dismiss();
        // isDownLoad = value < total;
        // // 更新下载进度
        // _progress = value / total;
        // if (!isDownLoad) {
        //   init();
        // }
        // setState(() {});
      },
      onError: (e) {
        if (!isDownLoad) SmartDialog.dismiss();
      },
    );
    // 更新状态
    if (isDownLoad) {
      isDownLoad = false;
      setState(() {});
    } else {
      SmartDialog.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            width: 282.w,
            height: 320.w,
            child: Stack(
              children: <Widget>[
                SizedBox(
                  width: double.infinity,
                  height: double.infinity,
                  child: Image.asset(Assets.imagesIconVersionUpdateBg,fit: BoxFit.fill,),
                ),
                SizedBox(
                  width: double.infinity,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(top: 160.w),
                        child: Text(
                          '${'发现新版本'.tr}！(v${widget.version})',
                          style: TextStyle(fontSize: 16.sp, color: const Color(0xff071D56), fontWeight: FontWeight.w600),
                        ),
                      ),
                      AppGaps.vGap10,
                      Expanded(
                        child: SingleChildScrollView(
                          child: Text(
                            widget.upDateContent,
                            style: TextStyle(fontSize: 14.sp, color: const Color(0xff071D56), fontWeight: FontWeight.w400),
                          ),
                        ).paddingSymmetric(horizontal: 10.w),
                      ),
                      AppGaps.vGap10,
                      // getProgressView(),
                      isDownLoad ? getLinearProgress() : getButtonView(),
                      // Visibility(visible: !isDownLoad, child: getButtonView()),
                      AppGaps.vGap10,
                    ],
                  ),
                ),
                // 右上角按钮
                Positioned(
                  right: 0,
                  top: 0,
                  child: Container(
                    width: 40.w,
                    height: 40.w,
                    alignment: Alignment.center,
                    color: Colors.transparent,
                  ).clickOnce(() {
                    if (widget.isForce) {
                      AppToast.showWarning('${'请下载最新版本'.tr}!');
                      return;
                    }
                    Get.back();
                  }),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
